package lancoo.com.net.retrofitrxjava.interceptor;

import android.text.TextUtils;
import android.util.Log;


import org.json.JSONObject;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import lancoo.com.net.retrofitrxjava.network.Network;
import lancoo.com.net.utils.retrofitTools.EncryptUtil;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Created by IVAN on 2018/11/12.
 */

public class RequestEncryptInterceptor implements Interceptor {

    public static String Authorization;


    @Override
    public Response intercept(Chain chain) throws IOException {
//        String url = URLDecoder.decode(chain.request().url().toString(),"UTF-8");
        String url =chain.request().url().toString();
        Log.e("url",url);
        Request request = chain.request();

        if(url.contains("Gather") || url.contains("Cheat")){
            return addSecretParams(chain);
        }
        if(!url.contains("Decrypt")){
            RequestBody body = request.body();
            String paramsStr="";
            if (body != null) {
                Buffer buffer = new Buffer();
                body.writeTo(buffer);
                Charset charset = StandardCharsets.UTF_8;
                MediaType contentType = body.contentType();
                if (contentType != null) {
                    charset = contentType.charset(charset);
                }
                paramsStr = buffer.readString(charset);
                Log.e("aaaa","不加密的接口。。。paramsStr:"+paramsStr);
            }else{
                int index = url.indexOf("?");
                paramsStr=url.substring(index+1);
            }

            if(url.contains("DebrisPublicWeb.asmx/WS_Get")||url.contains("Service_Basic.asmx/WS_G_GetSubSystemServerInfoForAllSubject")){
                String urlDecode = URLDecoder.decode(chain.request().url().toString(),"UTF-8");
                Log.e("aaaa","urlDecode:"+urlDecode);
                Request.Builder builder = request.newBuilder();
                Request build = builder.url(urlDecode).build();
                return chain.proceed(build);
            }
            Log.e("aaaa","GET不加密的接口。。。paramsStr:"+paramsStr);
            if (!TextUtils.isEmpty(paramsStr)&&paramsStr.toLowerCase().contains("token")) {
                Log.e("aaaa","GET加密的接口。。。paramsStr:"+paramsStr);
                Headers headers = request.headers();
                String systemID = headers.get("systemID");
                if(!TextUtils.isEmpty(systemID)&&TextUtils.equals("624",systemID)){
                    return addSecretParams(chain);
                }else{
                    return notSecretParams(chain);
                }

            }else{

                Headers headers = request.headers();
                String systemID = headers.get("systemID");
                if(!TextUtils.isEmpty(systemID)&&TextUtils.equals("930",systemID)){
                    Request.Builder builder = request.newBuilder();
                    String appkey="bookeditormobile";
                    String appSecret="F8185D0C6969438399725F038E651371";
                    String nonce= UUID.randomUUID().toString();
                    String salt = (Network.serverTime + System.currentTimeMillis() - Network.localTime) + "";
                    String sign= EncryptUtil.MD5(appSecret+salt+nonce);
                    Log.e("teachMaterial","url:"+url);
                    Log.e("teachMaterial","sign:"+sign);
                    Log.e("teachMaterial","timestamp:"+salt);
                    Log.e("teachMaterial","nonce:"+nonce);
                    Log.e("teachMaterial","appkey:"+appkey);
                    Log.e("teachMaterial","Authorization:"+("Bearer "+Authorization));
                    builder.addHeader("sign",sign);
                    builder.addHeader("timestamp",salt);
                    builder.addHeader("nonce",nonce);
                    builder.addHeader("appkey",appkey);
                    builder.addHeader("Authorization","Bearer "+Authorization);
                    Log.e("pmp",Authorization+"教材的接口"+url);
                    Request build = builder
                            .url(url)
                            .build();
                    return chain.proceed(build);
                }else  if(!TextUtils.isEmpty(systemID)&&TextUtils.equals("624",systemID)){
                    return addSecretParams(chain);
                }
                return chain.proceed(request);
            }
        }
        return addSecretParams(chain);

    }

    private Response notSecretParams(Chain chain) throws IOException {
        String url =chain.request().url().toString();
        Request request = chain.request();
        String paramsStr="";
        if(TextUtils.equals("GET",request.method())){//get
            int index = url.indexOf("?");
            if(index>0){
                paramsStr=url.substring(index+1);
            }
        }else {
            RequestBody body = request.body();
            if (body != null) {
                Buffer buffer = new Buffer();
                body.writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = body.contentType();
                if (contentType != null) {
                    charset = contentType.charset(charset);
                }
                paramsStr = buffer.readString(charset);
                Log.e("aaaa","参数："+paramsStr);
            }
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                paramsStr);
        Request.Builder builder = request.newBuilder();
        if (request.body() != null) {
            Headers headers = request.headers();
            request.headers("");
            String systemID = headers.get("systemID");
            if(!TextUtils.isEmpty(systemID)&&TextUtils.equals("930",systemID)){
                String appkey="bookeditormobile";
                String appSecret="F8185D0C6969438399725F038E651371";
                String nonce= UUID.randomUUID().toString();
                String salt = (Network.serverTime + System.currentTimeMillis() - Network.localTime) + "";
                String sign= EncryptUtil.MD5(appSecret+salt+nonce);
                builder.addHeader("sign",sign);
                builder.addHeader("timestamp",salt);
                builder.addHeader("nonce",nonce);
                builder.addHeader("appkey",appkey);
                builder.addHeader("Authorization","Bearer "+Authorization);
                Log.e("teachMaterial","url:"+url);
                Log.e("teachMaterial","sign:"+sign);
                Log.e("teachMaterial","timestamp:"+salt);
                Log.e("teachMaterial","nonce:"+nonce);
                Log.e("teachMaterial","appkey:"+appkey);
                Log.e("teachMaterial","Authorization:"+("Bearer "+Authorization));
                Log.e("pmp",Authorization+"教材的接口"+url);
            }
            Request build = builder
                    .post(requestBody)
                    .build();
            return chain.proceed(build);
        } else {
            int index=url.indexOf("?");
            if (index>0) {
                url = url.substring(0,index);
            }
            Log.e("pmp",url);
            Headers headers = request.headers();
            request.headers("");
            String systemID = headers.get("systemID");
            if(!TextUtils.isEmpty(systemID)&&TextUtils.equals("930",systemID)){
                String appkey="bookeditormobile";
                String appSecret="F8185D0C6969438399725F038E651371";
                String nonce= UUID.randomUUID().toString();
                String salt = (Network.serverTime + System.currentTimeMillis() - Network.localTime) + "";
                String sign= EncryptUtil.MD5(appSecret+salt+nonce);
                builder.addHeader("sign",sign);
                builder.addHeader("timestamp",salt);
                builder.addHeader("nonce",nonce);
                builder.addHeader("appkey",appkey);
                builder.addHeader("Authorization","Bearer "+Authorization);
                Log.e("teachMaterial","url:"+url);
                Log.e("teachMaterial","sign:"+sign);
                Log.e("teachMaterial","timestamp:"+salt);
                Log.e("teachMaterial","nonce:"+nonce);
                Log.e("teachMaterial","appkey:"+appkey);
                Log.e("teachMaterial","Authorization:"+("Bearer "+Authorization));
                Log.e("pmp",Authorization+"教材的接口"+url);
            }
            Request build = builder
                    .url(url + "?" + paramsStr)
                    .build();
            return chain.proceed(build);
        }
    }

    private Response addSecretParams(Chain chain) throws IOException {
        String url =chain.request().url().toString();
        Request request = chain.request();
        String paramsStr="";
        if(TextUtils.equals("GET",request.method())){//get
            int index = url.indexOf("?");
            if(index>0){
                paramsStr=url.substring(index+1);
            }
        }else {
            RequestBody body = request.body();
            if (body != null) {
                Buffer buffer = new Buffer();
                body.writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = body.contentType();
                if (contentType != null) {
                    charset = contentType.charset(charset);
                }
                paramsStr = buffer.readString(charset);
            }
        }
        String AppKey ="yhstu2";
        try {
            Log.e("aaa", "加密前的paramsStr:" + paramsStr);
            paramsStr = EncryptUtil.EncryptCode(AppKey, paramsStr);
            Log.e("aaa", "加密后的paramsStr:" + paramsStr);
        } catch (Exception e) {
            Log.e("network error", e.toString());
        }
        String salt = (Network.serverTime + System.currentTimeMillis() - Network.localTime) + "";

        String toData = paramsStr;
        String sign = EncryptUtil.MD5(AppKey + salt + toData);
        Log.e("timestamp", salt);
        Log.e("platform", AppKey);
        Log.e("sign", sign);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                paramsStr);
        Request.Builder builder = request.newBuilder();
        builder.header("platform", AppKey)//加密因子
                .header("context","CONTEXT03")//上下文，用于验证当前环境
                .header("timestamp", salt)//时间戳
                .header("sign", sign);//校验码


        if (request.body() != null) {
            Request build = builder
                    .post(requestBody)
                    .build();
            return chain.proceed(build);
        } else {
            int index=url.indexOf("?");
            if (index>0) {
                url = url.substring(0,index);
            }

            Request build = builder
                    .url(url + "?" + paramsStr)
                    .build();
            return chain.proceed(build);
        }
    }


}
